package com.vivz.baby.service;

import java.util.List;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.ResultReceiver;
import android.util.Log;

import com.vivz.baby.domain.ParcelableLogsList;
import com.vivz.baby.proxy.LogProxy;

public class LogService extends IntentService {
	
	private static final String TAG = "LogService";

	public static final String ALL_LOGS = "allLogs";
	public static final String LOG_RECEIVER = "rec";
	public static final String LOG_URL = "log_url";

	private static String URL = "http://default-environment-2xgz38vab8.elasticbeanstalk.com/log/get";

	public LogService() {
		super(TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		final ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra(LOG_RECEIVER);

		// Here we retrieve the logs using proxy
		String url = intent.getStringExtra(LOG_URL);
		if (url == null) {
			url = URL;
		}

		Log.i(TAG, "url for fetching all logs : \n" + url);

		try {
			List<com.vivz.baby.persistence.model.Log> allLogs = LogProxy.getAllLogs(url);
			Bundle b = new Bundle();
			Parcelable parcelableLogsList = new ParcelableLogsList(allLogs);
			b.putParcelable(ALL_LOGS, parcelableLogsList);
			receiver.send(0, b);

		} catch (Exception e) {
			Log.e(TAG, "Error occured while retrieving all logs", e);
		}

	}

}
